package it.unibo.imola.utils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class GenericsUtils {

	public static <T> T[] getSameClassOf(List<?> listOfSuperClasses, Class<T> clazz) {
		return getInstancesArrayFromList(listOfSuperClasses, clazz, false);
	}

	public static <T> T[] getSameTypeOf(List<?> listOfSuperClasses, Class<T> clazz) {
		return getInstancesArrayFromList(listOfSuperClasses, clazz, true);
	}

	@SuppressWarnings("unchecked")
	private static <T> T[] getInstancesArrayFromList(List<?> listOfSuperClasses, Class<T> clazz, boolean includeSubclasses) {
		int res_size = 0;
		int i = 0;
		T[] res = null;
		ArrayList<Object> found_instances = new ArrayList<Object>(0);

		for (i = 0; i < listOfSuperClasses.size(); i++) {
			if (includeSubclasses) {
				if (clazz.isAssignableFrom(listOfSuperClasses.get(i).getClass())) {
					res_size++;
					found_instances.add(listOfSuperClasses.get(i));
				}
			} else {
				if (clazz.equals(listOfSuperClasses.get(i).getClass())) {
					res_size++;
					found_instances.add(listOfSuperClasses.get(i));
				}
			}
		}

		res = (T[]) Array.newInstance(clazz, res_size);

		for (i = 0; i < res_size; i++) {
			res[i] = (T) found_instances.get(i);
		}
		return res;
	}
}
